//
//  BubbleChatViewController.m
//  WEIMO
//
//  Created by Lixiaoyong on 13-6-26.
//  Copyright (c) 2013年 广州从兴电子开发有限公司. All rights reserved.
//

#import "BubbleChatViewController.h"

#import <QuartzCore/QuartzCore.h>

#import "FMManager.h"
#import "JSONKit.h"
#import "InterfaceDefine.h"
#import "MyDataObject.h"
#import "DLog.h"
#import "BubbleChatCell.h"

#define kChatCellMinHeight 50.0
#define kBottomSendViewHeight 50.0
#define kViewWidth self.view.frame.size.width
#define kTableViewRect (CGRectMake(0, 0, kViewWidth, self.view.frame.size.height - 44 - kBottomSendViewHeight))

@interface BubbleChatViewController ()
{
    NSInteger mChatStartPage;
    NSInteger mChatPageSize;
    NSCondition *mConditionLock;
}
@property (nonatomic,retain) NSMutableArray *chatMessageArray;  //消息数组
@property (nonatomic,retain) UITableView *chatTableView;        //消息显示tableView
@property (nonatomic,retain) UITextField *sendMessageTextField; //写消息内容
@property (nonatomic,retain) UIView *sendView;                  //发送消息界面
@property (nonatomic,retain) BubbleChatCell *sendMessageCell;   //发送消息cell
@property (nonatomic,retain) UIButton *keyboardDisappearButton; //让键盘消失
@property (nonatomic,retain) NSTimer *chatTimer;                //消息刷新
@end

@implementation BubbleChatViewController
@synthesize toUserId,toUserImageUrl;
@synthesize chatTableView;
@synthesize chatMessageArray;
@synthesize sendView;
@synthesize sendMessageTextField;
@synthesize sendMessageCell;
@synthesize keyboardDisappearButton;
@synthesize chatTimer;

- (void)dealloc
{
    self.toUserId = nil;
    self.toUserImageUrl = nil;
    self.chatMessageArray = nil;
    self.chatTableView = nil;
    self.sendMessageTextField = nil;
    self.sendView = nil;
    self.sendMessageCell = nil;
    self.keyboardDisappearButton = nil;
    [self.chatTimer invalidate];
    self.chatTimer = nil;
    [mConditionLock release];
    mConditionLock = nil;
    [super dealloc];
}

- (id)init
{
    self = [super init];
    if (self)
    {
        
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self hideTabBar];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self.chatTimer invalidate];
    
    //移除观察者
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    mChatStartPage = 1;
    mChatPageSize = 2000;
    mConditionLock = [[NSCondition alloc] init];
    
    [[UIBarButtonItem appearance] setTintColor:[UIColor blackColor]];
    
    self.view.backgroundColor = [UIColor colorWithRed:236.0/255 green:237.0/255 blue:241.0/255 alpha:1];
    
    CGRect rect = kTableViewRect;
    self.chatTableView = [[[UITableView alloc] initWithFrame:rect] autorelease];
    self.chatTableView.backgroundColor = [UIColor colorWithRed:236.0/255 green:237.0/255 blue:241.0/255 alpha:1];
    self.chatTableView.dataSource = self;
    self.chatTableView.delegate = self;
    //self.chatTableView.showsVerticalScrollIndicator = NO;
    self.chatTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.chatTableView];
    
    self.keyboardDisappearButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.keyboardDisappearButton.frame = rect;
    [self.keyboardDisappearButton addTarget:self action:@selector(clickedKeyboardDisappearEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.keyboardDisappearButton];
    self.keyboardDisappearButton.hidden = YES;
    
    //创建发送界面
    rect.origin.y = rect.origin.y + rect.size.height;
    rect.size.height = kBottomSendViewHeight;
    [self createSendMessageView:rect];
    
    //请求数据
    [self requestMessagesWithGoodFriend];
    
    //监听键盘事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keybordAppearChangeFrame:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keybordDisappearChangeFrame) name:UIKeyboardWillHideNotification object:nil];
    
    //启动定时刷新
    [self refreshChatMessage];
}

- (void)didReceiveMemoryWarning
{
    DEnter();
    [super didReceiveMemoryWarning];
}

#pragma mark - private methods

//隐藏TabBar
- (void)hideTabBar
{
    if (self.tabBarController.tabBar.hidden == YES)
    {
        return;
    }
    UIView *contentView;
    if ( [[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]] )
        contentView = [self.tabBarController.view.subviews objectAtIndex:1];
    else
        contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    contentView.frame = CGRectMake(contentView.bounds.origin.x,  contentView.bounds.origin.y,  contentView.bounds.size.width, contentView.bounds.size.height + self.tabBarController.tabBar.frame.size.height);
    self.tabBarController.tabBar.hidden = YES;
}

- (void)refreshChatMessage
{
    self.chatTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(requestMessagesWithGoodFriend) userInfo:nil repeats:YES];
}

//创建发送界面
- (void)createSendMessageView:(CGRect)rect
{
    self.sendView = [[[UIView alloc] initWithFrame:rect] autorelease];
    //self.sendView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.sendView];
    
    UIImage *sendImage = [UIImage imageNamed:@"sendbg.png"];
    sendImage = [sendImage stretchableImageWithLeftCapWidth:5 topCapHeight:22];
    UIImageView *sendImageView = [[[UIImageView alloc] initWithImage:sendImage] autorelease];
    [sendImageView setFrame:CGRectMake(0, 0, rect.size.width, rect.size.height)];
    [self.sendView addSubview:sendImageView];
    
    rect.size.width = rect.size.width - 90;
    rect = CGRectMake(10, 5, rect.size.width, 40);
    self.sendMessageTextField = [[[UITextField alloc] initWithFrame:rect] autorelease];
    self.sendMessageTextField.borderStyle = UITextBorderStyleRoundedRect;
    self.sendMessageTextField.backgroundColor = [UIColor whiteColor];
    self.sendMessageTextField.returnKeyType = UIReturnKeySend;
    self.sendMessageTextField.delegate = self;
    self.sendMessageTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [self.sendView addSubview:self.sendMessageTextField];
    
    rect.origin.x = rect.origin.x + rect.size.width + 10;
    rect.size.width = 60;
    UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sendBtn.frame = rect;
    [sendBtn setBackgroundImage:[UIImage imageNamed:@"sendbutton"] forState:UIControlStateNormal];
    [sendBtn addTarget:self action:@selector(sendButtonClickedEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.sendView addSubview:sendBtn];
}

//请求数据
- (void)requestMessagesWithGoodFriend
{
    NSString *userId = [[FMManager sharedInstance] userId];
    if (!userId || userId.length <= 0 || !self.toUserId || self.toUserId.length <= 0)
    {
        return;
    }
    
    NSString *url = [NSString stringWithFormat:@"%@/%@",kHttpHost,kQueryPrivateinformation];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setValue:[NSString stringWithFormat:@"%d",mChatStartPage] forKey:@"startPage"];
    [dic setValue:[NSString stringWithFormat:@"%d",mChatPageSize] forKey:@"pageSize"];
    [dic setValue:self.toUserId forKey:@"toUserid"];
    [dic setValue:userId forKey:@"fromUserid"];
    NSString *post = [dic JSONString];
    [dic release];
    
    DLog(@"url:%@,post:%@",url,post);
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    [request appendPostData:[post dataUsingEncoding:NSUTF8StringEncoding]];
    [request setRequestMethod:@"POST"];
    [request setDelegate:self];
    [request startAsynchronous];
}

//重组数据
/*
 *value1:消息内容
 *value2:发送时间
 *value3:是否本人
 *value4:头像url
 */
- (void)structureDatasToShow:(NSMutableArray *)array
{
    //加锁
    [mConditionLock lock];
    
    //填充数据
    int lastNumber = 0;//上一次历史数据
    if (self.chatMessageArray)
    {
        lastNumber = self.chatMessageArray.count;
    }
    self.chatMessageArray = [[[NSMutableArray alloc] init] autorelease];
    
    NSString *userId = [[FMManager sharedInstance] userId];
    for (int i=0; i<array.count; i++)
    {
        MyDataObject *item = [array objectAtIndex:i];
        if ([item.value3 isEqualToString:userId])
        {
            item.value3 = @"2";
            item.value4 = [NSString stringWithFormat:@"%@/photo/%@/small_%@",kHttpHost,userId,[[FMManager sharedInstance] userPhotoName]];
        }
        else
        {
            item.value3 = @"1";
            item.value4 = self.toUserImageUrl;
        }
        
        [self.chatMessageArray addObject:item];
    }
    
    //刷新显示
    [self.chatTableView reloadData];
    
    //判断是否有新数据滚动到页底
    if (self.chatMessageArray.count > lastNumber)
    {
        [self tableViewScrollToBottom];
    }
    
    //解锁
    [mConditionLock unlock];
}

//tableView滚动到底端
- (void)tableViewScrollToBottom
{
    if (self.chatMessageArray.count > 0)
    {
        float contentHeight = self.chatTableView.contentSize.height;
        float frameHeight = self.chatTableView.frame.size.height;
        float oY = contentHeight - frameHeight;
        if (oY > 0)
        {
            [self.chatTableView setContentOffset:CGPointMake(0.0, oY)];
        }
    }
}

//键盘出现调整frame
- (void)keybordAppearChangeFrame:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    CGSize ksize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    
    float time = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    float oY = self.view.frame.size.height - ksize.height - kBottomSendViewHeight;
    CGRect rect = kTableViewRect;
    rect.size.height = oY - rect.origin.y;
    self.chatTableView.frame = rect;
    [self tableViewScrollToBottom];
    self.keyboardDisappearButton.frame = rect;
    self.keyboardDisappearButton.hidden = NO;
    
    rect.origin.y = oY;
    rect.size.height = kBottomSendViewHeight;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:time];
    self.sendView.frame = rect;
    [UIView commitAnimations];
}

//键盘消失调整frame
- (void)keybordDisappearChangeFrame
{
    CGRect rect = kTableViewRect;
    rect.size.height = rect.size.height + 44;
    self.chatTableView.frame = rect;
    [self tableViewScrollToBottom];
    self.keyboardDisappearButton.frame = rect;
    self.keyboardDisappearButton.hidden = YES;
    
    rect.origin.y = rect.origin.y + rect.size.height;
    rect.size.height = kBottomSendViewHeight;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.01];
    self.sendView.frame = rect;
    [UIView commitAnimations];
}

//发送内容到服务器
- (void)sendMessageToServer
{
    //插入数据
    NSString *content = self.sendMessageTextField.text;
    if (!content || content.length <= 0)
    {
        return;
    }
    
    [mConditionLock lock];
    
    MyDataObject *item = [[MyDataObject alloc] init];
    item.value1 = content;
    item.value3 = @"2";
    item.value4 = [NSString stringWithFormat:@"%@/photo/%@/small_%@",kHttpHost,[[FMManager sharedInstance] userId],[[FMManager sharedInstance] userPhotoName]];
    if (self.chatMessageArray == nil)
    {
        self.chatMessageArray = [[[NSMutableArray alloc] init] autorelease];
    }
    
    [self.chatMessageArray insertObject:item atIndex:0];
    [self.chatTableView reloadData];
    
    [self tableViewScrollToBottom];
    
    [item release];
    self.sendMessageTextField.text = @"";
    
    //显示发送指示器
    int count = self.chatMessageArray.count;
    if (count > 0)
    {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(count - 1) inSection:0];
        self.sendMessageCell = (BubbleChatCell *)[self.chatTableView cellForRowAtIndexPath:indexPath];
        [self.sendMessageCell showIndicatorView];
    }
    
    [mConditionLock unlock];
    
    //发送数据
    NSString *userId = [[FMManager sharedInstance] userId];
    if (!userId || userId.length <= 0 || !self.toUserId || self.toUserId.length <= 0)
    {
        return;
    }
    
    NSString *url = [NSString stringWithFormat:@"%@/%@",kHttpHost,kSendPrivateinformation];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setValue:self.toUserId forKey:@"fromUserid"];
    [dic setValue:userId forKey:@"toUserid"];
    [dic setValue:content forKey:@"postMessages"];
    NSString *post = [dic JSONString];
    [dic release];
    
    DLog(@"url:%@,post:%@",url,post);
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    [request appendPostData:[post dataUsingEncoding:NSUTF8StringEncoding]];
    [request setRequestMethod:@"POST"];
    [request setDelegate:self];
    [request startAsynchronous];
}

#pragma mark - button event

//点击发送按钮
- (void)sendButtonClickedEvent
{
    [self sendMessageToServer];
    [self.sendMessageTextField resignFirstResponder];
}

//键盘消失
- (void)clickedKeyboardDisappearEvent
{
    if (self.sendMessageTextField)
    {
        [self.sendMessageTextField resignFirstResponder];
    }
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    [self sendMessageToServer];
    
    return YES;
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.chatMessageArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *chatCellDefine = @"chatCellDefine";
    BubbleChatCell *cell = [tableView dequeueReusableCellWithIdentifier:chatCellDefine];
    if (cell == nil)
    {
        cell = [[[BubbleChatCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:chatCellDefine] autorelease];
    }
    
    MyDataObject *item = [self.chatMessageArray objectAtIndex:(self.chatMessageArray.count - 1 - indexPath.row)];
    [cell refreshFrameWithData:item withWidth:kViewWidth];
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyDataObject *item = [self.chatMessageArray objectAtIndex:(self.chatMessageArray.count - 1 - indexPath.row)];
    CGSize size = [BubbleChatContentHeight getStringLength:item.value1];
    float height = size.height > kChatCellMinHeight ? (size.height + 40.0) : (kChatCellMinHeight + 20.0);
    return height;
}

#pragma mark - ASIHTTPRequestDelegate

- (void)requestFailed:(ASIHTTPRequest *)request
{
    
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSString *urlString = [NSString stringWithFormat:@"%@",request.url];
    NSRange range = [urlString rangeOfString:@"/"];
    if (range.location != NSNotFound)
    {
        NSArray *array = [urlString componentsSeparatedByString:@"/"];
        urlString = [array objectAtIndex:(array.count - 1)];
    }
    
    NSData *data = [request responseData];
    NSArray *result = [data objectFromJSONData];
    if ([urlString isEqualToString:kQueryPrivateinformation])       //查询聊天记录
    {
        if (result.count > 0)
        {
            NSMutableArray *netDatas = [[[NSMutableArray alloc] init] autorelease];
            NSString *status = [result objectAtIndex:0];
            if ([status isEqualToString:kResponseOk])
            {
                NSDictionary *dicArray = [result objectAtIndex:1];
                NSArray *array = [dicArray objectForKey:@"data"];
                for (int i=0; i<array.count; i++)
                {
                    NSDictionary *dic = [array objectAtIndex:i];
                    MyDataObject *item = [[MyDataObject alloc] init];
                    item.value1 = [dic objectForKey:@"postMessages"];
                    item.value2 = [dic objectForKey:@"sendTime"];
                    item.value3 = [NSString stringWithFormat:@"%@",[dic objectForKey:@"toUserid"]];
                    [netDatas addObject:item];
                    [item release];
                }
            }
            
            [self structureDatasToShow:netDatas];
            
            DLog(@"获取列表成功");
        }
    }
    else                                                            //发送消息
    {
        if (result.count > 0)
        {
            NSString *status = [result objectAtIndex:0];
            if ([status isEqualToString:kResponseOk])
            {
                NSString *dic = [result objectAtIndex:1];
                DLog(@"私信发送成功:%@",dic);
            }
        }
        
        if (self.sendMessageCell)
        {
            [self.sendMessageCell hideIndicatorView];
        }
        self.sendMessageCell = nil;
    }
}

@end